//
//  SubmitOrderViewController.swift
//  worldexchange
//
//  Created by xionghao on 2019/2/15.
//  Copyright © 2019 xionghao. All rights reserved.
//

import UIKit
import InputKit
import RxSwift
import RxCocoa

class SubmitOrderViewController: QMUICommonViewController,UITextFieldDelegate {
    
    @IBOutlet weak var typeView: UISegmentedControl!
    
    @IBOutlet weak var rateLabelValue: UILabel!
    
    @IBOutlet weak var priceWrapper: UIView!
    
    @IBOutlet weak var priceTF: TXLimitedTextField!
    
    @IBOutlet weak var toMoneyLabel: UILabel!
    
    @IBOutlet weak var toMoneyWrapper: UIView!
    
    @IBOutlet weak var fromMoneyWrapper: UIView!
    
    @IBOutlet weak var fromMoneyLabel: UILabel!
    
    @IBOutlet weak var storeWrapper: UIView!
    
    @IBOutlet weak var storeLabel: UILabel!
    
    @IBOutlet weak var timeWrapper: UIView!
    
    @IBOutlet weak var timeLabel: UILabel!
    
    @IBOutlet weak var fromTipsLabel: UILabel!
    
    @IBOutlet weak var priceTipsLabel: UILabel!
    
    @IBOutlet weak var exchangeTipLabel: UILabel!
    
    @IBOutlet weak var cityTipsLabel: UILabel!
    
    @IBOutlet weak var timeTipsLabel: UILabel!
    
    var time:String?
    
    
    var isBuying:Bool = true
    
    var money:Double = 0.00
    
    
    var rate:RateItem!

    @IBOutlet weak var moneyTipsLabel: UILabel!
    @IBOutlet weak var moneyLabel: UILabel!
    @IBOutlet weak var btnSubmit: QMUIFillButton!
    
    @IBAction func submitClick(_ sender: QMUIButton) {
        
        checkForm()
    }
    
    
    
    
    func checkForm()  {
        if self.priceTF.text == "" {
            QMUITips.showInfo("InputMoney".localized())
            return
        }
        
//        if self.rate.money.rates.count > 1 {
//            let range = self.rate.link.split(separator: "-")
//            let money = Double(self.priceTF.text!) ?? 0.00
//            if range.count  == 2 {
//                let min = Double(range[0]) ?? 0.00
//                let max = Double(range[1]) ?? 0.00
//                if money < min && money > max {
//                    QMUITips.showInfo("当前汇率只适用于".localized())
//                }
//            } else {
//                let min = Double(range[0]) ?? 0.00
//
//            }
//        }
        
        
        if self.time == nil {
            QMUITips.showInfo("chooseTime".localized())
            return
        }
        
       
        submitOrder()
    }
    
    
    private func submitOrder(){
        let token = userData!.token
        let title = self.isBuying ? rate.money.ex_title : defaultCurrency
        let ex_title = self.isBuying ? defaultCurrency : rate.money.ex_title
        QMUITips.showLoading(in: self.view)
        provider.rx.request(WE.submit(token: token, title: title, ex_title: ex_title, type: isBuying ? 0 : 1, money: priceTF.text!, ones: rate.id, city: rate.contact_id, date: self.timeLabel.text!))
        .mapString()
            .subscribe(onSuccess: { (res) in
                QMUITips.hideAllTips()
                if let result =  ApiResult.deserialize(from: res) {
                    if result.code == 200 {
                        QMUITips.showSucceed("Success")
                        self.navigationController?.popViewController(animated: true)
                    } else {
                        QMUITips.showError(result.message)
                    }
                }
                
            }) { (error) in
                QMUITips.hideAllTips()
                print(error)
        }
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = "Appointment".localized()
        
        setupView()
        
        // Do any additional setup after loading the view.
    }
    
      let disposeBag = DisposeBag()
    
    func setupView()  {
        self.toMoneyWrapper.qmui_borderPosition = [.left,.top,.right,.bottom]
        self.toMoneyWrapper.layer.cornerRadius = 5
        
        self.fromMoneyWrapper.qmui_borderPosition = [.left,.top,.right,.bottom]
        self.fromMoneyWrapper.layer.cornerRadius = 5
        
        self.storeWrapper.qmui_borderPosition = [.left,.top,.right,.bottom]
        self.storeWrapper.layer.cornerRadius = 5
        
        self.priceWrapper.qmui_borderPosition = [.left,.top,.right,.bottom]
        self.priceWrapper.layer.cornerRadius = 5
        
        self.timeWrapper.qmui_borderPosition = [.left,.top,.right,.bottom]
        self.timeWrapper.layer.cornerRadius = 5
        
        self.timeWrapper.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(onChangeTime))
        self.timeWrapper.addGestureRecognizer(tap)
        self.priceTF.delegate = self
        self.fromTipsLabel.text = "我的货币".localized()
        self.priceTipsLabel.text = "兑换金额".localized()
        self.exchangeTipLabel.text = "兑换货币".localized()
        self.cityTipsLabel.text = "领取城市".localized()
        self.timeTipsLabel.text = "预约时间".localized()
        self.moneyTipsLabel.text = "可换金额".localized()
        
        self.priceTF.limitedType = .price
        // this means, that only five ints can be inputted
        self.priceTF.limitedPrefix = 10
        // this means, that only five decimal can be inputted
        self.priceTF.limitedSuffix = 2
        self.priceTF.rx.text
            .subscribe(onNext: { [weak self] (value) in
                self?.refreshMoney()
                
                }, onError: { (error) in
            }, onCompleted: nil, onDisposed: nil)
            .disposed(by: disposeBag)
        
    }
    
    func refreshMoney() {
        let moneyValue = self.priceTF.text ?? ""
        var money = 0.00
        if moneyValue == "" {
            money = 0.00
        } else {
            money = Double(moneyValue) ?? 0.00
        }
     
        let buying = Double(rate.buying)!
        let selling = Double(rate.selling)!
        let total = isBuying ? buying * money : money / selling
       
        self.moneyLabel.text = String(format: "%.4f", total)
    }
    
    @objc func onChangeTime(){
        let pickerVc = DatePickerViewController()
        let modalVc = QMUIModalPresentationViewController()
        modalVc.contentViewController = pickerVc
        modalVc.animationStyle = .slide
        modalVc.contentViewMargins = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
        pickerVc.selectBlock = {
            time in
            if time != "" {
                self.time = time
            }
            modalVc.hideWith(animated: true, completion: { (_) in
                self.refreshView()
            })
           
            
        }
        
        modalVc.showWith(animated: true, completion: nil)
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if self.money > 0 {
            self.priceTF.text = "\(self.money)"
        }
        
        refreshView()
    }
    @IBAction func onChangeValue(_ sender: UISegmentedControl) {
        self.isBuying = sender.selectedSegmentIndex == 0
        self.refreshView()
        
    }
    
    func refreshView() {
        self.typeView.setTitle("buyingLabel".localized(), forSegmentAt: 0)
        self.typeView.setTitle("sellingLabel".localized(), forSegmentAt: 1)
        self.timeLabel.text = self.time == nil ? "chooseTime".localized() : self.time
        self.btnSubmit.setTitle("btnSubmit".localized(), for: .normal)
        
        self.typeView.selectedSegmentIndex = isBuying ? 0 : 1
        
        self.rateLabelValue.text = "textExchangeRate".localized() + (self.isBuying ? "\(self.rate.buying)" : "\(self.rate.selling)")
        
        self.fromMoneyLabel.text = self.isBuying ?  self.rate.money.ex_title : defaultCurrency
        self.toMoneyLabel.text = self.isBuying ?  defaultCurrency : self.rate.money.ex_title
        self.storeLabel.text = currentShop?.title
        self.refreshMoney()
        
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destination.
     // Pass the selected object to the new view controller.
     }
     */
    
}
